
import { createStore, createLogger } from 'vuex';
import menus from './modules/menus.js';
import roles from './modules/roles.js';
import users from './modules/users.js';
import { login, verifyToken } from '@/api/common/web.js'
import { router } from "@/router"
import { toast } from "@/composables/util"
import {
    setToken,
    removeToken
} from '@/composables/auth'
import BlogList from "@/pages/front/blogList/index.vue";
import BlogDetail from "@/pages/front/blogDetail/index.vue";



const state = () => ({
    name: '我是主模块',
    // 侧边宽度
    asideWidth: "250px",
    userInfo:{},
    menuList: [
        {
            path:"/index",
            title:"后台首页",
            icon: "House"
        },
        {
            path:"/article",
            title: "文章管理",
            icon: "EditPen"
        },
        {
            path:"/category",
            title: "分类管理",
            icon: "Files"
        },
        {
            path:"/tag",
            title: "标签管理",
            icon: "Collection"
        },
        {
            path:"/tool",
            title: "工具管理",
            icon: "Tools"
        },
        {
            path:"/user",
            title: "用户管理",
            icon: "User"
        }
    ]
})
const mutations = {
    // 展开/缩起侧边
    handleAsideWidth(state) {
        state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px"
    },
    SET_USERINFO(state, userinfo) {
        state.userInfo = userinfo
    }
}

const actions = {
    // 登录
    login({ commit }, form) {
        return new Promise((resolve, reject) => {
            login(form).then(res => {
                const token = res.data.data.token
                setToken(token)
                resolve(token)
            }).catch(err => reject(err))
        })
    },
    // 获取当前登录用户信息
    getinfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            verifyToken().then(res => {
                commit("SET_USERINFO", res.data.data)  //只能通过commit进行赋值
                resolve(res.data.data)
            }).catch(err => reject(err))
        })
    },
    getMenus({ commit, state }) {
        return new Promise((resolve, reject) => {
            resolve(state.menuList);
        }).catch(err => reject(err))
    },
    // 退出登录
    logout({ commit }) {
        // 移除cookie里的token
        removeToken()
        // 清除当前用户状态 vuex
        commit("SET_USERINFO", {})
    }
}


const debug = process.env.NODE_ENV !== 'production';

export default createStore({
    state,
    mutations,
    actions,

    modules: {
        menus,
        roles,
        users,
    },
    strict: debug,
    plugins: debug ? [createLogger()] : []
})